<template>
	<uni-popup ref="popup" type="bottom">
		<view>
			<view v-if="prop.type != 'img'" class="item one border-bottom" @click="videoFun(0)">拍摄视频</view>
			<view
				v-if="prop.type != 'video'"
				class="item border-bottom"
				:class="{ one: prop.type === 'img' }"
				@click="imgFun(0)"
			>
				拍摄照片
			</view>
			<view v-if="prop.type != 'img'" class="item border-bottom" @click="videoFun(1)">从相册选择视频</view>
			<view v-if="prop.type != 'video'" class="item border-bottom" @click="imgFun(1)">从相册选择照片</view>
			<view class="line"></view>
			<view class="item uni-color-main" @click="close">取消</view>
		</view>
	</uni-popup>
</template>
<script setup>
import ossUpload from '/utils/ossUpload/index.js';
import { ref } from 'vue';
const prop = defineProps({
	// img video  img/video
	type: {
		type: String,
		default: 'img'
	}
});
const emits = defineEmits(['done']);
const popup = ref('');
function open() {
	const seleteMediaMode = uni.getStorageSync('selete-media-mode'),
		{ osName } = uni.getSystemInfoSync();
	if (seleteMediaMode || osName === 'ios') popup.value.open();
	else
		uni.showModal({
			title: '相机权限使用说明',
			content: '用于拍照、录制或上传视频图片等场景，是否允许使用？',
			confirmText: '允许',
			cancelText: '禁止',
			success: (cc) => {
				if (cc.confirm) {
					popup.value.open();
					uni.setStorageSync('selete-media-mode', 1);
				} else
					uni.showToast({
						title: '访问授权失败',
						icon: 'none'
					});
			}
		});
}
function close() {
	popup.value.close()
	uni.hideLoading()
}

function imgFun(type) {
	popup.value.close();
	uni.chooseImage({
		sourceType: [type ? 'album' : 'camera'],
		count: 1,
		success: (res) => {
			uni.showLoading({
				title: '上传中,请稍等...'
			})
			ossUpload
				.uploadFile(res.tempFilePaths[0], 1)
				.then((file) => {
					emits('done', file);
					close();
				})
				.catch(() => {
					close();
				});
		}
	});
}
function videoFun(type) {
	popup.value.close();
	uni.chooseVideo({
		sourceType: [type ? 'album' : 'camera'],
		success: (res) => {
			uni.showLoading({
				title: '上传中,请稍等...'
			})
			if (res.size / 1024 / 1024 > 1024) {
				uni.showToast({
					title: '文件不能超过1G',
					icon: 'none'
				});
				close();
				return;
			}
			ossUpload
				.uploadFile(res.tempFilePath, 0)
				.then((file) => {
					emits('done', file);
					uni.saveVideoToPhotosAlbum({
						filePath: res.tempFilePath,
						success: function () {
							console.log('save success');
						}
					});
					close();
				})
				.catch(() => {
					close();
				});
		}
	});
}
defineExpose({ open, close });
</script>
<style lang="scss" scoped>
.item {
	width: 100vw;
	height: 108rpx;
	line-height: 108rpx;
	text-align: center;
	background: $uni-white;
}
.one {
	border-radius: 32rpx 32rpx 0rpx 0rpx;
}
.border-bottom {
	border-bottom: 2rpx solid $uni-F5F5F5;
}

.line {
	width: 100vw;
	height: 20rpx;
	background: $uni-F5F5F5;
}
</style>
